import { FormInstance } from 'antd';
import debounce from 'lodash/debounce';
import { makeAutoObservable, runInAction } from 'mobx';
import loginLogApi from '../../api/loginLogApi';
import { dayjs2Date } from '../../utils/dateUtil';

export default class LoginLog {

  loading: boolean;
  detailLoading: boolean;
  data: any[];
  record: any;
  detail: any;
  current: number;
  pageSize: number;
  total: number;
  conditions: object;

  constructor() {
    this.loading = false;
    this.detailLoading = false;
    this.data = [];
    this.record = null;
    this.detail = null;
    this.current = 0;
    this.pageSize = 10;
    this.total = 0;
    this.conditions = this.getDefaultConditions();
    makeAutoObservable(this);
  }

  async fetchData(username: string, loginDate: any, pageNumber: number) {
    if (this.loading) {
      return;
    }

    let createdAt = dayjs2Date(loginDate);
    createdAt = createdAt ? createdAt.substring(0, 10) : '';
    runInAction(() => {
      this.loading = true;
    });
    const res: any = await loginLogApi.query(username, createdAt, pageNumber, this.pageSize);
    const list: any[] = res.data?.list || [];
    this.selectRecord(null);
    runInAction(() => {
      this.data = list;
      this.current = res.data?.current || 0;
      this.total = res.data?.total || 0;
      this.loading = false;
      this.conditions = {
        username,
        loginDate,
        pageNumber
      };
    });
  }

  async fetchDetail() {
    if (this.detailLoading) {
      return;
    }

    runInAction(() => {
      this.detailLoading = true;
    });
    const res: any = await loginLogApi.find(this.record?.id);
    runInAction(() => {
      this.detail = res.data;
      this.detailLoading = false;
    });
  }

  selectRecord(record: any) {
    runInAction(() => {
      this.record = record
    });
  }

  setPageSize(pageSize: number) {
    runInAction(() => {
      this.pageSize = pageSize;
    });
  }

    getDefaultConditions() {
      return {
        username: '',
        loginDate: null,
        pageNumber: 0
      };
    }
  
    resetConditions(form: FormInstance<any>) {
      runInAction(() => {
        this.conditions = this.getDefaultConditions();
        debounce(() => form.resetFields(), 50)();
      });
    }

};
